package cn.jingyuan.bee.enums.mybatis.type;

import cn.jingyuan.bee.enums.EnumInteger;
import cn.jingyuan.bee.enums.EnumString;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.EnumTypeHandler;
import org.apache.ibatis.type.JdbcType;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;


/**
 * 枚举自动转换器
 */
public class EnumAutoTypeHandler<E extends Enum<E>> extends BaseTypeHandler<E> {

    private final BaseTypeHandler typeHandler;

    public EnumAutoTypeHandler(Class<E> type) {
        if (type == null) {
            throw new IllegalArgumentException("Type argument cannot be null");
        }

        if (EnumInteger.class.isAssignableFrom(type)) {
            // 如果实现了 EnumInteger 则使用我们自定义的转换器
            typeHandler = new EnumTypeIntegerHandler(type);
        } else if (EnumString.class.isAssignableFrom(type)) {
            // 如果实现了 EnumString 则使用我们自定义的转换器
            typeHandler = new EnumTypeStringHandler(type);
        } else {
            // 默认转换器 也可换成 EnumOrdinalTypeHandler
            typeHandler = new EnumTypeHandler<>(type);
        }
    }

    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, E parameter, JdbcType jdbcType) throws SQLException {
        typeHandler.setNonNullParameter(ps, i, parameter, jdbcType);
    }

    @Override
    public E getNullableResult(ResultSet rs, String columnName) throws SQLException {
        Object result = typeHandler.getNullableResult(rs, columnName);
        if (null == result) {
            return null;
        }
        return (E) result;
    }

    @Override
    public E getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        Object result = typeHandler.getNullableResult(rs, columnIndex);
        if (null == result) {
            return null;
        }
        return (E) result;
    }

    @Override
    public E getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        Object result = typeHandler.getNullableResult(cs, columnIndex);
        if (null == result) {
            return null;
        }
        return (E) result;
    }

}
